package com.project.im.web.config;

import com.alibaba.fastjson.JSON;
import com.project.im.app.vo.ResponseVO;
import com.project.im.common.enums.ResponseCode;
import com.project.im.common.exception.WebAuthenticationException;
import com.project.im.common.util.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

@Slf4j
public class WebAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("【认证失败】请求地址: {} 异常信息: {}", request.getRequestURI(), authException.getMessage());
        if (authException instanceof WebAuthenticationException webAuthenticationException) {
            WebUtils.write(response, JSON.toJSONString(ResponseVO.fail(webAuthenticationException.getCode(), webAuthenticationException.getMessage())));
            return;
        }
        WebUtils.write(response, JSON.toJSONString(ResponseVO.fail(ResponseCode.AR100)));
    }
}
